package com.linkhub.oms.admin.modules.product.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.linkhub.oms.admin.common.exception.ExceptionFactory;
import com.linkhub.oms.admin.modules.product.domain.param.ShopProductQueryParam;
import com.linkhub.oms.admin.modules.product.domain.vo.ShopProductImportResultVO;
import com.linkhub.oms.admin.modules.product.domain.vo.ShopProductVO;
import com.linkhub.oms.admin.modules.product.service.ShopProductBizService;
import com.linkhub.oms.common.enums.mp.PlatFormEnum;
import com.linkhub.oms.common.enums.mp.SuccessfulEnum;
import com.linkhub.oms.common.enums.product.SkuMatchStatusEnum;
import com.linkhub.oms.common.response.PageDTO;
import com.linkhub.oms.common.util.QtOptionalUtil;
import com.linkhub.oms.common.util.QtStreamUtil;
import com.linkhub.oms.dao.mapper.ShopProductSkuEntityMapper;
import com.linkhub.oms.dao.mpservice.IShopProductService;
import com.linkhub.oms.dao.mpservice.IShopProductSkuService;
import com.linkhub.oms.dao.mpservice.IShopService;
import com.linkhub.oms.data.sync.service.ShopifyDataSyncBizService;
import com.linkhub.oms.entity.ShopEntity;
import com.linkhub.oms.entity.ShopProductEntity;
import com.linkhub.oms.entity.ShopProductSkuEntity;
import com.linkhub.oms.entity.resulttype.ShopProductListResultEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.linkhub.oms.component.excel.util.EasyExcelUtil;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @Description: ShopProductBizService
 * @Author: echo
 * @Date: 2024/3/22 17:01
 * @Version: 1.0
 */
@Slf4j
@Service
public class ShopProductBizServiceImpl implements ShopProductBizService {

    @Resource
    private IShopProductSkuService shopProductSkuService;
    @Resource
    private ShopProductSkuEntityMapper shopProductSkuEntityMapper;
    @Resource
    private IShopService shopService;
    @Resource
    private ShopifyDataSyncBizService shopifyDataSyncBizService;
    @Resource
    private IShopProductService shopProductService;


    @Override
    public PageDTO<ShopProductVO> pageShopProducts( ShopProductQueryParam shopProductQueryParam ) {
        ShopProductQueryParam param = shopProductQueryParam;
        // 查询当前用户商店
        String userId = param.getUserId();
        List<ShopEntity> shops = shopService.listByUserId(userId);
        if (CollUtil.isEmpty(shops)) {
            return new PageDTO<>();
        }
        List<String> sysShopIds = QtStreamUtil.map(shops, ShopEntity::getSysShopId);
        MPJLambdaWrapper<ShopProductSkuEntity> wrapper = shopProductSkuService.getShopProductListQueryWrapper(param.getMatchStatus(), param.getSearchType(), param.getKeyword(), sysShopIds);

        Page<ShopProductListResultEntity> objectPage = new Page<>(param.getPage(), param.getSize());
        objectPage.setOptimizeJoinOfCountSql(false);

        Page<ShopProductListResultEntity> page = shopProductSkuEntityMapper.selectJoinPage(objectPage, ShopProductListResultEntity.class, wrapper);

        PageDTO<ShopProductVO> res = shopProductVoBuilder(shops, page);

        return res;
    }

    @Override
    public Integer manualUpdateShopProducts( String userId ) {
        List<ShopEntity> shops = shopService.listByUserId(userId, SuccessfulEnum.YES);
        if (CollUtil.isEmpty(shops)) {
            return 0;
        }
        Integer res = 0;
        for (ShopEntity shop : shops) {
            res += shopifyDataSyncBizService.syncShopProducts(shop);

        }

        return res;
    }

    @Override
    public ShopProductImportResultVO importManualOrders( String userId, MultipartFile shopProductExcel ) {
        ShopProductImportResultVO shopProductImportResultVO = new ShopProductImportResultVO();
        EasyExcelUtil.isValidFile(shopProductExcel);
        try {
            List<ShopProductImportResultVO.ShopProductImportResult> shopProductImportResults = new ArrayList<>();
            int successTotal = 0;

            // 使用 Hutool 提供的 ExcelReader 来读取 Excel 文件
            ExcelReader reader = ExcelUtil.getReader(shopProductExcel.getInputStream(), "Sheet1"); // 指定工作表名称

            // 读取所有数据，返回 List<Map<String, Object>>，每个 Map 对应一行数据
            List<Map<String, Object>> rows = reader.readAll();

            // 遍历每一行数据
            for (Map<String, Object> row : rows) {
                // 使用列索引来获取数据
                String platform = Objects.toString(row.get("* Platform"), "");
                String shopName = Objects.toString(row.get("* Store Name"), "");
                String productName = Objects.toString(row.get("* Product Name"), "");
                String sku = Objects.toString(row.get("* Product SKU"), "");
                String productImageUrl = Objects.toString(row.get("Product Image URL"), "");
                    try {
                        // 不支持的平台
                        if (StringUtils.isNotBlank(platform) && !PlatFormEnum.SHIPO.getDesc().equals(platform)) {
                            String message = "Platform \"" + platform + "\" is not supported";
                            ShopProductImportResultVO.ShopProductImportResult shopProductImportResult = createShopProductImportResult(shopName, productName, sku, message);
                            shopProductImportResults.add(shopProductImportResult);
                            continue;
                        }

                        if (StringUtils.isBlank(productName) || StringUtils.isBlank(sku)) {
                            String message = "Product Name or sku cannot be empty";
                            ShopProductImportResultVO.ShopProductImportResult shopProductImportResult = createShopProductImportResult(shopName, productName, sku, message);
                            shopProductImportResults.add(shopProductImportResult);
                            continue;
                        }

                        ShopEntity shopEntity = shopService.getUserShopByShopName(userId, shopName);
                        // 商店不存在
                        if (shopEntity == null) {
                            String message = "Store \"" + shopName + "\" does not exist";
                            ShopProductImportResultVO.ShopProductImportResult shopProductImportResult = createShopProductImportResult(shopName, productName, sku, message);
                            shopProductImportResults.add(shopProductImportResult);
                            continue;
                        }
                        // 商店非shipo商店
                        if (!PlatFormEnum.SHIPO.equals(shopEntity.getPlatForm())) {
                            String message = "The store \"" + shopName + "\" is not a shipo platform store";
                            ShopProductImportResultVO.ShopProductImportResult shopProductImportResult = createShopProductImportResult(shopName, productName, sku, message);
                            shopProductImportResults.add(shopProductImportResult);
                            continue;
                        }
                        String sysShopId = shopEntity.getSysShopId();

                        // sku已存在
                        ShopProductSkuEntity shopProductSkuEntity = shopProductSkuService.getShopProductBysku(sysShopId, sku);
                        if (shopProductSkuEntity != null) {
                            String message = "sku \"" + sku + "\" already exists";
                            ShopProductImportResultVO.ShopProductImportResult shopProductImportResult = createShopProductImportResult(shopName, productName, sku, message);
                            shopProductImportResults.add(shopProductImportResult);
                            continue;
                        }

                        saveProduct(sysShopId, productName, sku, productImageUrl);

                        successTotal++;
                    } catch (Exception e) {
                        log.error(e.getMessage());
                        ShopProductImportResultVO.ShopProductImportResult shopProductImportResult = createShopProductImportResult(shopName, productName, sku, e.getMessage());
                        shopProductImportResults.add(shopProductImportResult);
                    }
            }

            shopProductImportResultVO.setFailList(shopProductImportResults);
            shopProductImportResultVO.setFailTotal(shopProductImportResults.size());
            shopProductImportResultVO.setSuccessTotal(successTotal);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException("Failed to parse Excel file.");
        }
        return shopProductImportResultVO;
    }

    private ShopProductImportResultVO.ShopProductImportResult createShopProductImportResult( String shopName, String productName, String sku, String message ) {
        ShopProductImportResultVO.ShopProductImportResult shopProductImportResult = new ShopProductImportResultVO.ShopProductImportResult();
        shopProductImportResult.setShopName(shopName);
        shopProductImportResult.setProductName(productName);
        shopProductImportResult.setSku(sku);
        shopProductImportResult.setMessage(message);
        return shopProductImportResult;
    }

    private void saveProduct( String sysShopId, String productName, String sku, String productImageUrl ) {
        // 产品名称获取产品信息
        ShopProductEntity shopProductEntity = shopProductService.getShopProductByProductName(sysShopId, productName);
        String nowTime = String.valueOf(LocalDateTime.now());
        long productId;
        if (shopProductEntity == null) {
            // 新增商品
            productId = IdUtil.getSnowflake().nextId();
            shopProductEntity = new ShopProductEntity();
            shopProductEntity.setSysShopId(sysShopId);
            shopProductEntity.setProductId(productId);
            shopProductEntity.setTitle(productName);
            shopProductEntity.setCreatedAt(nowTime);
            shopProductEntity.setUpdatedAt(nowTime);

            shopProductService.save(shopProductEntity);
        } else {
            // 已有商品添加sku
            productId = shopProductEntity.getProductId();
        }
        long skuId = IdUtil.getSnowflake().nextId();
        ShopProductSkuEntity shopProductSkuEntity = new ShopProductSkuEntity();
        shopProductSkuEntity.setSysShopId(sysShopId);
        shopProductSkuEntity.setProductId(productId);
        shopProductSkuEntity.setSkuId(skuId);
        shopProductSkuEntity.setTitle(sku);
        shopProductSkuEntity.setSku(sku);
        shopProductSkuEntity.setImgUrl(productImageUrl);
        shopProductSkuEntity.setCreatedAt(nowTime);
        shopProductSkuEntity.setUpdatedAt(nowTime);

        shopProductSkuService.save(shopProductSkuEntity);
    }

    @Override
    public List<ShopProductVO> listAssignShopProducts( String sysShopId ) {
        List<ShopProductSkuEntity> shopProductSkuEntityList = shopProductSkuService.getShopProductListBySysShopId(sysShopId);
        List<ShopProductVO> resultList = QtStreamUtil.map(shopProductSkuEntityList, this::convertShopProducts);
        return resultList;
    }

    private ShopProductVO convertShopProducts( ShopProductSkuEntity shopProductSkuEntity ) {
        ShopProductVO vo = new ShopProductVO();
        vo.setSysShopId(shopProductSkuEntity.getSysShopId());
        vo.setProductId(shopProductSkuEntity.getProductId().toString());
        vo.setSkuId(shopProductSkuEntity.getSkuId().toString());
        vo.setSkuTitle(shopProductSkuEntity.getTitle());
        vo.setSku(shopProductSkuEntity.getSku());
        vo.setShopProductImgUrl(shopProductSkuEntity.getImgUrl());
        return vo;
    }

    private PageDTO<ShopProductVO> shopProductVoBuilder( List<ShopEntity> shops, Page<ShopProductListResultEntity> page ) {
        PageDTO<ShopProductVO> res = new PageDTO<>();
        res.setTotal(page.getTotal());
        res.setSize(page.getSize());
        res.setCurrent(page.getCurrent());
        res.setPages(page.getPages());
        List<ShopProductVO> shopProducts = QtStreamUtil.map(page.getRecords(), this::convert);
        Map<String, ShopEntity> shopMap = QtStreamUtil.toMap(shops, ShopEntity::getSysShopId);
        QtStreamUtil.peek(shopProducts, vo -> vo.setShopName(QtOptionalUtil.of(shopMap.get(vo.getSysShopId())).map(ShopEntity::getShopName).orElse("")));
        res.setRecords(shopProducts);
        return res;
    }

    private ShopProductVO convert( ShopProductListResultEntity entity ) {
        ShopProductVO vo = new ShopProductVO();
        vo.setSysShopId(entity.getSysShopId());
        vo.setProductId(entity.getProductId().toString());
        vo.setSkuId(entity.getSkuId().toString());
        vo.setTitle(entity.getProductTitle());
        vo.setSkuTitle(entity.getTitle());
        vo.setSku(entity.getSku());
        vo.setShopProductImgUrl(entity.getImgUrl());

        String matchSkuId = entity.getMatchSkuId();
        vo.setMatchSkuId(matchSkuId);
        SkuMatchStatusEnum matchStatus = StringUtils.isBlank(matchSkuId) ? SkuMatchStatusEnum.UN_MATCH : SkuMatchStatusEnum.MATCH;
        vo.setMatchStatus(matchStatus.getCode());
        vo.setMatchSku(entity.getMatchSku());
        vo.setMatchStatusDesc(matchStatus.getDesc());
        vo.setMatchProductImgUrl(entity.getMatchProductImgUrl());
        return vo;

    }

}
